<template>
    <div class="screen-wrapper">
        <div class="screen">
            <div>
                <div class="title">GPX 生产状况，环境，消耗品的实时监控</div>
            </div>
            <div class="line"></div>
            <div id="dd">
                <el-table :data="tableData" border style="width:100%;margin-top:20px"
                    :header-cell-style="headerStyle">
                    <el-table-column label="产线" align="center" prop="lineName" min-width="80"></el-table-column>
                    <el-table-column label="生产状态" align="center" min-width="100">
                        <template slot-scope="scope">
                            机器名：{{ scope.row.machineName }}
                            <br />
                            程序名： {{ scope.row.recipeName }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="machineStatus" label="机器状态" align="center" :formatter="formatSatus">
                        <template slot-scope="{row}">
                            <span v-if="row.machineStatus == 1">
                                <img src="../../assets/img/greenStatus.svg" alt="绿色状态" width="40px">
                            </span>
                            <span v-else-if="row.machineStatus == 2">
                                <img src="../../assets/img/yellowStatus.svg" alt="黄色状态" width="40px">
                            </span>
                            <span v-else>
                                <img src="../../assets/img/redStatus.svg" alt="红色状态" width="40px">
                            </span>
                            <p style="margin:0;">{{ row.machineStatusDesc }}</p>
                        </template>
                    </el-table-column>
                    <el-table-column prop="utilizationRate" label="稼动率" align="center" width="220">
                        <template slot-scope="scope">
                            <v-chart class="chart" :option="utilizationOption(scope.$index)" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="period" label="周期" class-name="period-option-chart-cell" align="center"
                        width="290">
                        <template slot-scope="scope">
                            <v-chart class="chart period-option-chart" :option="periodOption(scope.$index)" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="materialUsageInfo" label="材料使用情况" align="center" width="220">
                        <template slot-scope="scope">
                            <div @click="showDialogMaterial(scope.$index)">
                                <v-chart class="chart" :option="materialOption1(scope.$index)" />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="materialUsageInfo" align="center" width="220">
                        <template slot-scope="scope">
                            <div @click="showDialogSolder(scope.$index)">
                                <v-chart class="chart" :option="materialOption2(scope.$index)" />
                            </div>
                        </template>
                    </el-table-column>

                </el-table>
            </div>

            <div v-if="showDialog">
                <el-dialog title="材料使用情况" :visible.sync="dialogVisibleMaterial" width="40%" :append-to-body="true">
                    <v-chart class="chart1" :option="materialOption1(dialogIndex)" />
                </el-dialog>
            </div>
            <div v-if="showDialog">
                <el-dialog title="材料使用情况" :visible.sync="dialogVisibleSolder" width="40%" :append-to-body="true">
                    <v-chart class="chart2" :option="materialOption2(dialogIndex)" />
                </el-dialog>
            </div>
        </div>
    </div>
</template>
<script>
import { getMaterailData, gpxDateSSEUrl } from '@/network/gpx'
import autofit from 'autofit.js'

export default {
    name: 'material',
    props: {},

    // 数据
    data() {
        return {
            tableData: [],
            showDialog: false,
            dialogVisibleMaterial: false,
            dialogVisibleSolder: false,
            dialogIndex: '',
            eventSource: null
        };
    },
    // 生命周期 - 创建完成（访问当前this实例）
    created() { },
    // 生命周期 - 挂载完成（访问DOM元素）
    mounted() {
        this.getTableData()
        // 大屏适配
        // autofit.init({
        //   dh: 1080,
        //   dw: 1920,
        //   el: "#app",
        //   resize: true,
        // }, false)
    },
    computed: {
    },
    methods: {
        showDialogMaterial(rowindex) {
            this.dialogVisibleMaterial = true
            this.showDialog = true
            this.dialogIndex = rowindex
        },
        showDialogSolder(rowindex) {
            this.dialogVisibleSolder = true
            this.showDialog = true
            this.dialogIndex = rowindex
        },
        // 饼图
        utilizationOption(index) {
            return {
                tooltip: {
                    trigger: 'item',
                    position: function (pos, params, dom, rect, size) {
                        var obj = { top: 60 };
                        obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
                        return obj;
                    },
                    formatter: '{b} <br/>{c}'
                },
                series: [
                    {
                        name: 'Access From',
                        type: 'pie',
                        center: ['50%', '50%'], // 设置饼图位置
                        radius: '90%',
                        data: [
                            {
                                value: this.tableData[index].utilizationRate.operatingTime,
                                name: '操作时间',
                                itemStyle: { color: '#5470C6' } // 蓝色
                            },
                            {
                                value: this.tableData[index].utilizationRate.autoProductionTime,
                                name: '生产时间',
                                itemStyle: { color: 'green' } // 绿色
                            },
                            {
                                value: this.tableData[index].utilizationRate.cleaningTime,
                                name: '清洗时间',
                                itemStyle: { color: '#FAC858' } // 黄色
                            },
                            {
                                value: this.tableData[index].utilizationRate.errorTime,
                                name: '错误时间',
                                itemStyle: { color: '#dc143c' } // 红色
                            },
                            {
                                value: this.tableData[index].utilizationRate.otherTime,
                                name: '其他时间',
                                itemStyle: { color: 'gray' } // 灰色
                            },
                            {
                                value: this.tableData[index].utilizationRate.readyTime,
                                name: '准备时间',
                                itemStyle: { color: '#73C0DE' } // 青色
                            },
                            {
                                value: this.tableData[index].utilizationRate.waitNextTime,
                                name: '等后时间',
                                itemStyle: { color: '#FC8452' } // 橙色
                            },
                            {
                                value: this.tableData[index].utilizationRate.waitPreviousTime,
                                name: '等前时间',
                                itemStyle: { color: '#9A60B4' } // 紫色
                            }
                        ],
                        label: {
                            show: true,
                            position: 'inner',
                            formatter: '{d}%', // 显示百分比
                            fontSize: 12
                        }
                    }
                ]
            }
        },

        //柱状图
        periodOption(index) {
            return {
                grid: {
                    // left: '5%',
                    height: "86%",//高度
                    // y: "6%", // y 偏移量
                    bottom: '1em',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: this.tableData[index].period.lastPanelCycleTimes.map((v, i) => i + 1),//.map(v => v.panelId || ''),
                    //刻度对齐
                    axisTick: {
                        alignWithLabel: true
                    }
                },
                yAxis: {
                    type: 'value',
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: '{c}'
                },
                backgroundColor: this.tableData[index].period.lastPanelAvgCycleTime > this.tableData[index].period.maxCycleTime ?
                    'rgba(255, 0, 0, 0.5)' : (this.tableData[index].period.lastPanelAvgCycleTime > this.tableData[index].period.thresholdCycleTime ?
                        'yellow' : ''),
                series: [
                    {
                        data: this.tableData[index].period.lastPanelCycleTimes.map(v => v.cycleTime),
                        type: 'bar',
                        //设置柱状图宽度
                        barWidth: 10,
                        markLine: {
                            symbol: ['none', 'none'],
                            data: [
                                {
                                    yAxis: this.tableData[index].period.recipeCycleTime,
                                    lineStyle: {
                                        type: 'dashed',
                                        color: '#F04134',
                                        width: this.tableData[index].period.recipeCycleTime > 0 ? 1 : 0,
                                    },
                                    label: {
                                        //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
                                        position: "middle",
                                        fontSize: 12,
                                        color: '#F04134',
                                        formatter: this.tableData[index].period.recipeCycleTime > 0 ? `标准${this.tableData[index].period.recipeCycleTime}s` : "",
                                    },
                                },
                                //第二条线
                                {
                                    yAxis: this.tableData[index].period.lastPanelAvgCycleTime,
                                    lineStyle: {
                                        type: "dashed",  //虚实
                                        color: "green",  //颜色
                                        width: 1,   //基线粗细
                                    },
                                    label: {
                                        //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
                                        position: "middle",
                                        fontSize: 12,  //文字大小
                                        color: "green",
                                        formatter: `平均${this.tableData[index].period.lastPanelAvgCycleTime}s`, // 基线名称
                                    }
                                }
                            ]
                        }
                    },

                ],
            };
        },
        //进度条
        materialOption1(index) {
            return {
                grid: {
                    left: '10',
                    top: '10',
                    right: '30',
                    bottom: '0',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    splitLine: { show: false },
                    axisLabel: { show: false },
                    axisTick: { show: false },
                    axisLine: { show: false }
                },
                yAxis: {
                    type: 'category',
                    axisTick: { show: false },
                    axisLine: { show: false },
                    axisLabel: {
                        fontSize: 10
                    },
                    data: ['底座', '后刮刀', '前刮刀', '钢网']
                },
                series: [
                    {
                        name: '',
                        type: 'bar',
                        barWidth: 14,
                        data: [
                            Math.min(this.tableData[index].materialUsageInfo.backup.backupCurrCnt, this.tableData[index].materialUsageInfo.backup.backupMaxCnt), // 进度条不超过最大值
                            Math.min(this.tableData[index].materialUsageInfo.rearSqueegee.squeegeeCurrCnt, this.tableData[index].materialUsageInfo.rearSqueegee.squeegeeMaxCnt),
                            Math.min(this.tableData[index].materialUsageInfo.frontSqueegee.squeegeeCurrCnt, this.tableData[index].materialUsageInfo.frontSqueegee.squeegeeMaxCnt),
                            Math.min(this.tableData[index].materialUsageInfo.mask.maskCurrCnt, this.tableData[index].materialUsageInfo.mask.maskMaxCnt)
                        ],
                        label: {
                            show: true,
                            offset: [0, 1],
                            formatter: (params) => {
                                // 显示真实数值，不受最大值限制
                                let realValue = [
                                    this.tableData[index].materialUsageInfo.backup.backupCurrCnt,
                                    this.tableData[index].materialUsageInfo.rearSqueegee.squeegeeCurrCnt,
                                    this.tableData[index].materialUsageInfo.frontSqueegee.squeegeeCurrCnt,
                                    this.tableData[index].materialUsageInfo.mask.maskCurrCnt
                                ][params.dataIndex];
                                return `${realValue}`;
                            },
                            color: 'rgba(0,0,0,.7)',
                            fontSize: 12
                        },
                        itemStyle: {
                            normal: {
                                barBorderRadius: 10,
                                color: (params) => {
                                    let value = [
                                        this.tableData[index].materialUsageInfo.backup.backupCurrCnt,
                                        this.tableData[index].materialUsageInfo.rearSqueegee.squeegeeCurrCnt,
                                        this.tableData[index].materialUsageInfo.frontSqueegee.squeegeeCurrCnt,
                                        this.tableData[index].materialUsageInfo.mask.maskCurrCnt
                                    ][params.dataIndex];

                                    let threshold = [
                                        this.tableData[index].materialUsageInfo.backup.backupThresholdCnt,
                                        this.tableData[index].materialUsageInfo.rearSqueegee.squeegeeThresholdCnt,
                                        this.tableData[index].materialUsageInfo.frontSqueegee.squeegeeThresholdCnt,
                                        this.tableData[index].materialUsageInfo.mask.maskThresholdCnt
                                    ][params.dataIndex];

                                    let max = [
                                        this.tableData[index].materialUsageInfo.backup.backupMaxCnt,
                                        this.tableData[index].materialUsageInfo.rearSqueegee.squeegeeMaxCnt,
                                        this.tableData[index].materialUsageInfo.frontSqueegee.squeegeeMaxCnt,
                                        this.tableData[index].materialUsageInfo.mask.maskMaxCnt
                                    ][params.dataIndex];

                                    // 根据当前值与阈值和最大值的比较，返回对应颜色
                                    if (value < threshold) {
                                        return '#32CD32'; // 绿色
                                    } else if (value >= threshold && value < max) {
                                        return '#FFD700'; // 黄色
                                    } else {
                                        return '#DC143C'; // 红色
                                    }
                                }
                            }
                        },
                        zlevel: 1
                    },
                    {
                        name: '进度条背景',
                        type: 'bar',
                        label: {
                            show: true,
                            position: 'right',
                            offset: [0, 0],
                            fontSize: 13
                        },
                        barGap: '-100%',
                        barWidth: 14,
                        data: [
                            this.tableData[index].materialUsageInfo.backup.backupMaxCnt,
                            this.tableData[index].materialUsageInfo.rearSqueegee.squeegeeMaxCnt,
                            this.tableData[index].materialUsageInfo.frontSqueegee.squeegeeMaxCnt,
                            this.tableData[index].materialUsageInfo.mask.maskMaxCnt
                        ],
                        color: 'rgba(0,0,0,.2)',
                        itemStyle: {
                            normal: {
                                barBorderRadius: 10
                            }
                        }
                    }
                ]
            };
        },
        //电池图
        materialOption2(index) {
            const currSeriesData = [
                Math.min(parseInt(this.tableData[index].materialUsageInfo.solder.remainderSolderPercent), 100),
                Math.min(parseInt(this.tableData[index].materialUsageInfo.remainderSolventPercent), 100),
                Math.min(parseInt(this.tableData[index].materialUsageInfo.remainderPaperPercent), 100)
            ]
            return {
                grid: {
                    left: '-2%',
                    height: "85%", // 高度
                    y: "16%", // y 偏移量
                    containLabel: true
                },
                xAxis: {
                    axisLine: {
                        show: false // 是否显示坐标轴
                    },
                    axisTick: {
                        show: false // 是否显示坐标轴刻度
                    },
                    data: ['钢网', '酒精', '无尘纸'],
                },
                yAxis: {
                    show: false,
                    min: 0,
                    max: 100 // 最大值为100
                },
                label: {
                    show: true, // 开启显示
                    // formatter: '{c}%', // 显示百分号
                    formatter: params => `${currSeriesData[params.dataIndex]}%`.padStart(4),
                    // position: 'top', // 在上方显示
                    position: [0, -15], // 相对于图形包围盒左上角的位置。
                    textStyle: { // 数值样式
                        fontSize: 11
                    }
                },
                series: [
                    {
                        data: currSeriesData,
                        // data: [
                        //     {name:'锡膏',
                        //         value:Math.min(parseInt(this.tableData[index].materialUsageInfo.solder.remainderSolderPercent), 100)},
                        //     {name:'清洗剂',value:Math.min(parseInt(this.tableData[index].materialUsageInfo.remainderSolventPercent), 100)},
                        //     {name:'清洗纸',value:Math.min(parseInt(this.tableData[index].materialUsageInfo.remainderPaperPercent), 100)}
                        // ],
                        type: 'pictorialBar',
                        symbol: 'Rect', // 图形类型矩形
                        barWidth: '60%', // 设置柱状图宽度
                        itemStyle: {
                            normal: {
                                label: {
                                    show: false, // 开启显示
                                    formatter: '{c}%', // 显示百分号
                                    // position: 'top', // 在上方显示
                                    position: ['30%', '0%'], // 相对于图形包围盒左上角的位置。
                                    textStyle: { // 数值样式
                                        fontSize: 11
                                    }
                                },
                                color: function (params) {
                                    let colorList = [
                                        '#6495ED',
                                        '#03cfb4',//'#FFD700',
                                        '#32CD32',
                                    ];
                                    let colorItem = colorList[params.dataIndex];
                                    return colorItem;
                                }
                            }
                        },
                    },
                    {
                        name: '外框',
                        type: 'bar',
                        silent: true,
                        data: ['100', '100', '100'],
                        barWidth: '60%',
                        itemStyle: {
                            normal: {
                                color: 'rgba(76,105,125,0.1)', // 填充色
                                barBorderWidth: 0.5, // 边框宽度
                                borderColor: 'black' // 边框颜色
                            }
                        },
                        z: 10
                    }
                ],
            }
        },

        //发送请求
        async getTableData() {
            try {
                const res = await getMaterailData()
                console.log(res);
                if (res) {
                    if (res.data) {
                        this.tableData = res.data
                    }
                    else {
                        this.tableData = res;
                    }
                }
            } catch (error) {
                console.log(error);
            }
            this.startSSEListen();
        },
        //合并表头
        /*returm {rowspan: 1,colspan: 1}表示表格不变
          return (rowspan: 2,colspan: 1}表示表格向下合并一个单元格
          return {rowspan: 1,colspan: 2}表示表格向右合并一个单元格
          returm (rowspan: 0,colspan: 0}表示删除此单元格 */
        headerStyle({ row, columnIndex }) {
            if (columnIndex == 6) {
                return { display: "none" };
            }
            row[5].colSpan = 2;
            row[6].colSpan = 0;
            //设置表头颜色
            return {
                background: '#eef1f6', color: '#606266'
            }
        },
        formatSatus(row) {
            // console.log(row);
            if (row.machineStatus == 1) {
                return '正常'
            } else if (row.machineStatus == 2) {
                return '警告'
            } else if (row.machineStatus == 3) {
                return '异常'
            }
        },
        startSSEListen() {
            this.eventSource = new EventSource(gpxDateSSEUrl);
            let eventSource = this.eventSource;
            let esOpened = false;
            eventSource.addEventListener("open", function (e) {
                esOpened = true;
                console.log("EventSource started", e);
            }, false);
            eventSource.onmessage = event => {
                // const resultDiv = document.getElementById("result");
                console.log(event.data);
                const result = JSON.parse(event.data);
                if (!result.data) {
                    return;
                }
                const curr = result.data;
                let replaceIdx = -1;
                for (let i = 0; i < this.tableData.length; i++) {
                    if (this.tableData[i].machineName === curr.machineName) {
                        replaceIdx = i;
                        break;
                    }
                }
                if (replaceIdx >= 0) {
                    // this.tableData[replaceIdx] = curr;
                    this.$set(this.tableData, replaceIdx, curr);
                }
                else {
                    this.tableData.push(curr);
                }
            };
            eventSource.onerror = e => {
                console.log("EventSource failed", e);
                if (e.eventPhase == EventSource.CLOSED) {
                    console.log("Connection closed", e);
                    eventSource.close();
                    esOpened = false;
                }
                else {
                }
                esOpened && this.startSSEListen(); // 重连
            }
            eventSource.onclose = function (e) {
                console.log("EventSource closed", e);
                esOpened = false;
            }
        }
    },
    beforeRouteLeave(to, from, next) {
        // 导航离开当前路由的时候被调用，this可以被访问到
        // console.log(this) // 可以访问this
        // console.log('beforeRouteLeave')
        if (this.eventSource) {
            this.eventSource.close();
            this.eventSource = null;
        }
        next()
    }
}


</script>
<style lang="scss" scoped>
.chart {
    height: 130px;
    width: 200px;
    cursor: pointer;
}

.chart1 {
    height: 150px;
    width: 300px;
    cursor: pointer;
}

.chart2 {
    height: 150px;
    width: 300px;
    cursor: pointer;
}

.chart.period-option-chart {
    width: 270px;
}

// 无法应用此样式到最终结果
// .el-table {
//     .period-option-chart-cell{
//         >.cell{
//             padding:0;
//         }
//     }
// }

::v-deep {
    .el-dialog__body {
        display: flex;
        justify-content: center;
        align-items: center;

        >.chart-container {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
}


.title {
    font-size: 24px;
    margin-left: 100px;
    margin-bottom: 8px;
    // font-weight: bold;
    font-family: 思源宋体 SemiBold;
}

.line {
    background: linear-gradient(to left, #ffffff, #637ca0, #ffffff);
    height: 3px;
}
</style>
